package com.zzh.takeoutapp.wxapi;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;

import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.zzh.takeoutapp.config.Constants;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;


public class WXEntryActivity extends AppCompatActivity implements IWXAPIEventHandler {

    public int WX_LOGIN = 1;

    private IWXAPI iwxapi;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        iwxapi = WXAPIFactory.createWXAPI(this, Constants.APP_ID, false);
        iwxapi.handleIntent(getIntent(), this);

    }


    @Override
    public void onReq(BaseReq baseReq) {
    }


    //请求回调结果处理
    @Override
    public void onResp(BaseResp baseResp) {
        //微信登录为getType为1，分享为0
        if (baseResp.getType() == WX_LOGIN) {
            //登录回调
            SendAuth.Resp resp = (SendAuth.Resp) baseResp;
            switch (resp.errCode) {
                case BaseResp.ErrCode.ERR_OK:
                    String code = String.valueOf(resp.code);
                    //获取用户信息
                    getAccessToken(code);
                    break;
                case BaseResp.ErrCode.ERR_AUTH_DENIED://用户拒绝授权
                    break;
                case BaseResp.ErrCode.ERR_USER_CANCEL://用户取消
                    break;
                default:
                    break;
            }
        } else {
            //分享成功回调
            switch (baseResp.errCode) {
                case BaseResp.ErrCode.ERR_OK:
                    //分享成功
                    Toast.makeText(WXEntryActivity.this, "分享成功", Toast.LENGTH_LONG).show();
                    break;
                case BaseResp.ErrCode.ERR_USER_CANCEL:
                    //分享取消
                    Toast.makeText(WXEntryActivity.this, "分享取消", Toast.LENGTH_LONG).show();
                    break;
                case BaseResp.ErrCode.ERR_AUTH_DENIED:
                    //分享拒绝
                    Toast.makeText(WXEntryActivity.this, "分享拒绝", Toast.LENGTH_LONG).show();
                    break;
            }
        }
        finish();
    }

    private void getAccessToken(String code) {
        String
                getATUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="
                + Constants.APP_ID + "&secret=" + Constants.APP_SECRET + "&code="
                + code + "&grant_type=authorization_code";

        AsyncTask<String, Integer, HashMap<String, String>> getTokenTask = new AsyncTask<String, Integer, HashMap<String, String>>() {
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
            }

            @Override
            protected HashMap<String, String> doInBackground(String... params) {
                try {
                    String resultString = getInput2String(params[0]);
                    // 对sb进行jsonObject
                    JSONObject jsonObject;
                    jsonObject = new JSONObject(resultString);
                    String access_token_code = (String) jsonObject
                            .get("access_token");
                    String openId = jsonObject.getString("openid");
                    HashMap<String, String> hashMap = new HashMap<String, String>();
                    hashMap.put("access_token", access_token_code);
                    hashMap.put("openid", openId);
                    return hashMap;
                } catch (JSONException e) {
                    e.printStackTrace();
                    System.out.println(e);
                }
                return null;
            }

            @Override
            protected void onPostExecute(HashMap<String, String> result) {
                super.onPostExecute(result);

                String access_token = result.get("access_token");
                String openid = result.get("openid");
                getUID(access_token, openid);
            }
        };
        getTokenTask.execute(getATUrl);
    }

    private JSONObject result1;

    /*
     * https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=
     * OPENID 获取微信个人信息
     */
    private void getUID(String access_token, String openid) {
        String url = "https://api.weixin.qq.com/sns/userinfo?access_token="
                + access_token + "&openid=" + openid;

        AsyncTask<String, String, JSONObject> getUIDtask = new AsyncTask<String, String, JSONObject>() {
            @Override
            protected JSONObject doInBackground(String... params) {
                String resultString = getInput2String(params[0]);
                // 对sb进行jsonObject
                JSONObject jsonObject;
                try {
                    jsonObject = new JSONObject(resultString);
                    return jsonObject;
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(JSONObject result) {
                Log.e("wxen", result.toString());
                result1 = result;
            }
        };
        getUIDtask.execute(url);
    }

    /**
     * 访问微信连接返回inputstream工具类
     *
     * @param url1
     * @return
     */
    @SuppressWarnings("finally")
    public String getInput2String(String url1) {
        InputStream is = null;
        BufferedReader bf = null;
        String result = null;
        try {
            URL url = new URL(url1);
            HttpURLConnection httpConn = (HttpURLConnection) url
                    .openConnection();
            if (httpConn != null) {
                httpConn.setRequestMethod("GET");
                httpConn.setConnectTimeout(3000);
                int resCode = httpConn.getResponseCode();
                if (resCode == 200) {
                    is = httpConn.getInputStream();
                    if (is != null) {
                        bf = new BufferedReader(new InputStreamReader(is));
                        StringBuffer sb = new StringBuffer();
                        String ALine = null;
                        while ((ALine = bf.readLine()) != null) {
                            sb.append(ALine);
                        }
                        result = sb.toString();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bf != null) {
                try {
                    bf.close();
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return result;
        }
    }

}
